package demo.gateway.metric;

import org.springframework.stereotype.Component;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

@Component
public class GatewayMetricsCollector {


    // 使用原子类来统计各项指标
    public final AtomicLong totalRequests = new AtomicLong(0);
    public final AtomicLong errorRequests = new AtomicLong(0);
    public final AtomicLong totalResponseBytes = new AtomicLong(0);
    public final AtomicLong totalRequestBytes = new AtomicLong(0);
    public final AtomicInteger activeConnections = new AtomicInteger(0);
    public final AtomicInteger concurrentRequests = new AtomicInteger(0);

    // 使用队列存储响应时间，用于计算平均值
    public final Queue<Long> responseTimes = new ConcurrentLinkedQueue<>();

    // 记录上一次统计的时间戳，用于计算速率
    public long lastReportTime = System.currentTimeMillis();



    public void incrementRequests() {
        totalRequests.incrementAndGet();
        concurrentRequests.incrementAndGet();
    }

    public void decrementConcurrentRequests() {
        concurrentRequests.decrementAndGet();
    }

    public void recordError() {
        errorRequests.incrementAndGet();
    }

    public void recordResponseTime(long responseTime) {
        responseTimes.offer(responseTime);
        // 保持队列大小在合理范围内
        while (responseTimes.size() > 1000) {
            responseTimes.poll();
        }
    }

    public void recordBytes(long requestBytes, long responseBytes) {
        totalRequestBytes.addAndGet(requestBytes);
        totalResponseBytes.addAndGet(responseBytes);
    }

    public void connectionOpened() {
        activeConnections.incrementAndGet();
    }

    public void connectionClosed() {
        activeConnections.decrementAndGet();
    }
}
